<template>
	<div class="uni-forms-item" :class="{ 'uni-forms-item--border': border,
		'is-first-border': border && isFirstBorder, 'uni-forms-item-error': msg }">
		<div class="uni-forms-item__box">
			<div class="uni-forms-item__inner" :class="['is-direction-' + labelPos]">
				<div class="uni-forms-item__label" :style="{ width: labelWid ,
					justifyContent: justifyContent }">
					<slot name="left">
						<label v-if="required" class="is-required">*</label>
						<span v-if="leftIcon" class="label-icon" size="16"
							:type="leftIcon" :color="iconColor">span</span>
						<label class="label-label">{{ label }}</label>

						<div v-if="label" class="label-seat"></div>
					</slot>
				</div>
				<div class="uni-forms-item__content" :class="{
					'is-input-error-border': msg }"><slot></slot></div>
			</div>
			<div
				v-if="msg"
				class="uni-error-message"
				:class="{ 'uni-error-msg--boeder': border }"
				:style="{
				paddingLeft: labelLeft
				}">
				<label class="uni-error-message-label">{{ showMsg === 'undertext' ?
					msg : '' }}</label>
			</div>
		</div>
	</div>
</template>

<script>
  export default {
	  name: 'uniFormsItem',
  }
	</script>
<script setup>
/**
 * Field 输入框
 * @description 此组件可以实现表单的输入与校验，包括 "label" 和 "labelarea" 类型。
 * @tutorial https://ext.dcloud.net.cn/plugin?id=21001
 * @property {Boolean} 	required 			是否必填，左边显示红色"*"号（默认false）
 * @property {String} validateTrigger = [bind|submit]	校验触发器方式 默认 submit 可选
 * 	@value bind 	发生变化时触发
 * 	@value submit 	提交时触发
 * @property {String } 	leftIcon 			label左边的图标，限 uni-ui 的图标名称
 * @property {String } 	iconColor 			左边通过icon配置的图标的颜色（默认#606266）
 * @property {String } 	label 				输入框左边的文字提示
 * @property {Number } 	labelWidth 			label的宽度，单位px（默认65）
 * @property {String } 	labelAlign = [left|center|right] label的文字对齐方式（默认left）
 * 	@value left		label 左侧显示
 * 	@value center	label 居中
 * 	@value right	label 右侧对齐
 * @property {String } 	labelPosition = [top|left] label的文字的位置（默认left）
 * 	@value top	顶部显示 label
 * 	@value left	左侧显示 label
 * @property {String } 	errorMessage 		显示的错误提示内容，如果为空字符串或者false，则不显示错误信息
 * @property {String } 	name 				表单域的属性名，在使用校验规则时必填
 */
import {getCurrentInstance, reactive,ref, onMounted,onUnmounted,watch,computed, inject  } from 'vue'
const props=defineProps({
		// 自定义内容
		custom: {
			type: Boolean,
			default: false
		},
		// 是否显示报错信息
		showMessage: {
			type: Boolean,
			default: true
		},
		name: String,
		required: Boolean,
		validateTrigger: {
			type: String,
			default: ''
		},
		leftIcon: String,
		iconColor: {
			type: String,
			default: '#606266'
		},
		label: String,
		// 左边标题的宽度单位px
		labelWidth: {
			type: [Number, String],
			default: ''
		},
		// 对齐方式，left|center|right
		labelAlign: {
			type: String,
			default: ''
		},
		// lable的位置，可选为 left-左边，top-上边
		labelPosition: {
			type: String,
			default: ''
		},
		errorMessage: {
			type: [String, Boolean],
			default: ''
		},
		// 表单校验规则
		rules: {
			type: Array,
			default() {
				return [];
			}
		}
	})
	const {proxy} = getCurrentInstance()

	let errorTop = ref(false)
	let errorBottom = ref(false)
	let labelMarginBottom = ref('')
	let errorWidth = ref('')
	let errMsg = ref('')
	let val = ref('')
	let labelPos = ref('')
	let labelWid = ref('')
	let labelAli = ref('')
	let showMsg = ref('undertext')
	let border = ref(false)
	let isFirstBorder = ref(false)
	let isArray = ref(false)
	let arrayField = ref('')
	let formTrigger = ref('')
  let msg = computed(() => props.errorMessage || errMsg.value)
  let fieldStyle = computed(() => {
    let style = {};
			if (labelPos.value == 'top') {
				style.padding = '0 0';
				labelMarginBottom.value = '6px';
			}
			if (labelPos.value == 'left' && msg !== false && msg != '') {
				style.paddingBottom = '0px';
				errorBottom.value = true;
				errorTop.value = false;
			} else if (labelPos.value == 'top' && msg !== false && msg != '') {
				errorBottom.value = false;
				errorTop.value = true;
			} else {
				// style.paddingBottom = ''
				errorTop.value = false;
				errorBottom.value = false;
			}
			return style;
  })
	let justifyContent = computed(() => {
		if (labelAli.value === 'left') return 'flex-start';
			if (labelAli.value === 'center') return 'center';
			if (labelAli.value === 'right') return 'flex-end';
	})
	let labelLeft = computed(() => {
			return (labelPos.value === 'left' ? parseInt(labelWid.value) : 0) + 'px'
		})
	watch(()=>props.validateTrigger,(newValue,oldValue) =>{
		formTrigger.value = newValue
	})
  let	form = inject('data');
  let	group = getForm('uniGroup');
  let	formRules_item = [];
	let validator_item={}
	let __isUnmounted=false
	// create 初始化
	formTrigger.value = props.validateTrigger;
	// 处理 name，是否数组
	if (props.name && props.name.indexOf('[') !== -1 && props.name.indexOf(']') !== -1) {
		isArray.value = true;
		arrayField.value = props.name
		// fix by mehaotian 修改不修改的情况，动态值不检验的问题
		form.formData[props.name] = form._getValue(props.name, '')
	}
	onMounted(() => {
		if (form) {
			form.childrens.push(proxy);
		}
		init();
	})
	onUnmounted(() => {
		__isUnmounted = true
		unInit()
	})
		/**
	 * 获取父元素实例
	 */
	function getForm(name = 'uniForms') {
		let parent = proxy.$parent;
		let parentName = parent.$options.name;
		while (parentName !== name) {
			parent = parent.$parent;
			if (!parent) return false;
			parentName = parent.$options.name;
		}
		return parent;
	}
	function init() {
			if (form) {
				let { formRules, validator, formData, labelPosition, labelWidth, labelAlign, errShowType } = form;
				labelPos.value = props.labelPosition ? props.labelPosition : labelPosition;

				if(props.label){
					labelWid.value = (props.labelWidth ? props.labelWidth : (labelWidth||70))
				}else{
					labelWid.value =( props.labelWidth ? props.labelWidth : (labelWidth||'auto'))
				}
				if(labelWid.value && labelWid.value !=='auto') {
					labelWid.value +='px'
				}
				labelAli.value = props.labelAlign ? props.labelAlign : labelAlign;

				// 判断第一个 item
				if (!form.isFirstBorder) {
					form.isFirstBorder = true;
					isFirstBorder.value = true;
				}

				// 判断 group 里的第一个 item
				if (group) {
					if (!group.isFirstBorder) {
						group.isFirstBorder = true;
						isFirstBorder.value = true;
					}
				}

				border.value = form.border;
				showMsg.value = errShowType;
				let name = isArray.value ? arrayField.value : props.name;
				if(!name) return
				if (formRules && props.rules.length > 0) {
					if (!formRules[name]) {
						formRules[name] = {
							rules: props.rules
						}
					}
					validator.updateSchema(formRules);
				}
				formRules_item = formRules[name] || {};
				validator_item = validator;
			} else {
				labelPos.value = props.labelPosition || 'left';
				labelWid.value = props.labelWidth || 65;
				labelAli.value = props.labelAlign || 'left';
			}
		}
		function unInit(){
			if (form) {
				form.childrens.forEach((item, index) => {
					if (item === proxy) {
						form.childrens.splice(index, 1)
						delete form.formData[item.name]
					}
				})
			}
		}
		/**
		 * 移除该表单项的校验结果
		 */
		function clearValidate() {
			errMsg.value = '';
		}
		/**
		 * 子组件调用，如 easyinput
		 * @param {Object} value
		 */
	 	function setValue(value) {
			let name = isArray.value ? arrayField.value : props.name;
			if (name) {
				if (errMsg.value) errMsg.value = '';
				// 给组件赋值
				form.formData[name] = form._getValue(name, value);
				if (!formRules_item || (typeof formRules_item && JSON.stringify(formRules_item) === '{}')) return;
				 triggerCheck(form._getValue(props.name, value));
			}
		}
		/**
		 * 校验规则
		 * @param {Object} value
		 */
		 async function triggerCheck(value,formTrigger) {
			let promise = null;
			errMsg.value = '';
			// fix by mehaotian 解决没有检验规则的情况下，抛出错误的问题
			if (!validator_item || Object.keys(formRules_item).length === 0) return;
			const isNoField = isRequired(formRules_item.rules || []);
			let is_Trigger = isTrigger(formRules_item.validateTrigger, props.validateTrigger, form.validateTrigger);
			let result = null;
			if (!!is_Trigger || formTrigger) {
				let name = isArray.value ? arrayField.value : props.name;
				result = await validator_item.validateUpdate(
					{
						[name]: value
					},
					form.formData
				);
			}
			// 判断是否必填,非必填，不填不校验，填写才校验
			if (!isNoField && (value === undefined || value === '')) {
				result = null;
			}
			const inputComp = form.inputChildrens.find(child => child.rename === props.name);
			if ((is_Trigger ||　formTrigger) && result && result.errorMessage) {
				if (inputComp) {
					inputComp.errMsg = result.errorMessage;
				}
				if (form.errShowType === 'toast') {
					alert(result.errorMessage)
					// uni.showToast({
					// 	title: result.errorMessage || '校验错误',
					// 	icon: 'none'
					// });
				}
				if (form.errShowType === 'modal') {
					alert(result.errorMessage)
					// uni.showModal({
					// 	title: '提示',
					// 	content: result.errorMessage || '校验错误'
					// });
				}
			} else {
				if (inputComp) {
					inputComp.errMsg = '';
				}
			}

			errMsg.value = !result ? '' : result.errorMessage;
			// 触发validate事件
			form.validateCheck(result ? result : null);
			// typeof callback === 'function' && callback(result ? result : null);
			// if (promise) return promise
			return result ? result : null;
		}
		/**
		 * 触发时机
		 * @param {Object} event
		 */
		function isTrigger(rule, itemRlue, parentRule) {
			let rl = true;
			//  bind  submit
			if (rule === 'submit' || !rule) {
				if (rule === undefined) {
					if (itemRlue !== 'bind') {
						if (!itemRlue) {
							return parentRule === 'bind' ? true : false;
						}
						return false;
					}
					return true;
				}
				return false;
			}
			return true;
		}
		// 是否有必填字段
	  function isRequired(rules) {
			let isNoField = false;
			for (let i = 0; i < rules.length; i++) {
				const ruleData = rules[i];
				if (ruleData.required) {
					isNoField = true;
					break;
				}
			}
			return isNoField;
		}
		defineExpose({setValue})
</script>
<style lang="scss" scoped>
.uni-forms-item {
	position: relative;
	padding: 0px;
	label-align: left;
	color: #333;
	font-size: 14px;
}

.uni-forms-item__box {
	position: relative;
}

.uni-forms-item__inner {
	display: flex;
	padding-bottom: 22px;
}

.is-direction-left {
	flex-direction: row;
}

.is-direction-top {
	flex-direction: column;
}

.uni-forms-item__label {
	display: flex;
	flex-shrink: 0;
	box-sizing: border-box;
	flex-direction: row;
	align-items: center;
	width: 65px;
	padding: 5px 0;
	height: 36px;

	.label-label {
		font-size: 14px;
		color: #333;
	}
	.label-seat {
		margin-right: 5px;
	}
}

.uni-forms-item__content {
	/* #ifndef APP-NVUE */
	width: 100%;
	box-sizing: border-box;
	min-height: 36px;
	/* #endif */
	flex: 1;
}

.label-icon {
	margin-right: 5px;
	margin-top: -1px;
}

/* 必填 */
.is-required {
	 /* color: $uni-color-error; */
	color: #f00;
	font-weight: bold;
}

.uni-error-message {
	position: absolute;
	bottom: 0px;
	left: 0;
	label-align: left;
}

.uni-error-message-label {
	line-height: 22px;
	color: red;
	font-size: 12px;
}

.uni-error-msg--boeder {
	position: relative;
	bottom: 0;
	line-height: 22px;
}

.is-input-error-border {
	border-color: red;
}

.uni-forms-item--border {
	margin-bottom: 0;
	padding: 10px 0;
	border-top: 1px #eee solid;

	.uni-forms-item__inner {
		padding: 0;
	}
}

.uni-forms-item-error {
	// padding-bottom: 0;
}

.is-first-border {
	/* #ifndef APP-NVUE */
	border: none;
	/* #endif */
	/* #ifdef APP-NVUE */
	border-width: 0;
	/* #endif */
}

.uni-forms--no-padding {
	padding: 0;
}
</style>
